package com.hnas.core.app_common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class TestUtil {

	public static void main(String[] args) {
		try {
			String base64 =  TestUtil.ImageConverteStr("C:/Users/hongjie/Desktop/ttt/tiger.jpg");
			System.out.println("base64 ==> " + base64);
			boolean bl = TestUtil.GenerateImage(base64,"C:/Users/hongjie/Desktop/ttt/newtiger.jpg");
			System.out.println("GenerateImage  boolean ==> " + bl);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
     *  base64字符串生成图片
     * @param imgStr
     * @param imgFilePath
     * @return
     */
    public static boolean GenerateImage(String imgStr,String imgFilePath)
    { //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null || null == imgFilePath){
        	   return false;//图像数据为空
        }
        try
        {
        	BASE64Decoder decoder = new BASE64Decoder();
	        //Base64解码
	        byte[] b = decoder.decodeBuffer(imgStr);
	        for(int i=0;i<b.length;++i)
	        {
	            if(b[i]<0)
	            {//调整异常数据
	               b[i]+=256;
	            }
	        }
	        //生成jpeg图片
	        OutputStream out = new FileOutputStream(imgFilePath);
	        out.write(b,0,b.length);
	        out.flush();
	        out.close();
	        return true;
        }
        catch (Exception e)
        {
            return false;
        }
    } 


    /**
     * 图片转化成 base64字符串
     * @param imgStr
     * @return
     * @throws IOException
     */
    public static String ImageConverteStr(String imgStr) throws IOException
    { //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) {
        	return "";//图像数据为空
        }
        String str ="";
        try{
        	 BASE64Encoder encoder = new BASE64Encoder();
             FileInputStream inputStream = new FileInputStream(new File(imgStr));
             ByteArrayOutputStream output = new ByteArrayOutputStream();
             byte[] by = new byte[1024];
             int len = 0;
             while((len=inputStream.read(by))!=-1){
                  output.write(by, 0, len);
             }
             output.flush();
             output.close(); 
             str = encoder.encode(output.toByteArray());
        }catch(Exception e){
        	e.printStackTrace();
        }
        return str;
    } 
}
